package com.bigtotoro.shuiyincamera;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.RectF;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.SeekBar;
import android.widget.Toast;
import android.widget.VideoView;

import com.bigtotoro.shuiyincamera.adapter.SimpleAdapter3;
import com.bigtotoro.shuiyincamera.adapter_can_moved.ItemDragHelperCallback;
import com.bigtotoro.shuiyincamera.adapter_can_moved.OnDragVHListener;
import com.bigtotoro.shuiyincamera.adapter_can_moved.OnItemMoveListener;
import com.bigtotoro.shuiyincamera.editimage.utils.CompatResourceUtils;
import com.bigtotoro.shuiyincamera.editimage.view.SpaceItemDecoration;
import com.bigtotoro.shuiyincamera.image.AddWaterMark02Activity;
import com.bigtotoro.shuiyincamera.image.Palette02Activity;
import com.bigtotoro.shuiyincamera.image.RemoveWaterMark2Activity;
import com.bigtotoro.shuiyincamera.model.MyArt;
import com.bigtotoro.shuiyincamera.model.VideoEditMenu;
import com.bigtotoro.shuiyincamera.util.FileUtils;
import com.bigtotoro.shuiyincamera.util.ModelSingle;
import com.bigtotoro.shuiyincamera.util.MyUtils;
import com.bigtotoro.shuiyincamera.util.VideoItem;
import com.bigtotoro.shuiyincamera.util.VideoUtil;
import com.bigtotoro.shuiyincamera.video.VideoAddWater2Activity;
import com.bigtotoro.shuiyincamera.video.VideoConcatActivity;
import com.bigtotoro.shuiyincamera.video.VideoCropActivity;
import com.bigtotoro.shuiyincamera.video.VideoFilterActivity;
import com.bigtotoro.shuiyincamera.video.VideoMusicActivity;
import com.bigtotoro.shuiyincamera.video.VideoRemoveWaterActivity;
import com.bigtotoro.shuiyincamera.video.VideoSpeedActivity;
import com.bigtotoro.shuiyincamera.video.VideoSpliceActivity;
import com.bigtotoro.shuiyincamera.video.trim.VideoTrimmerActivity;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.umeng.analytics.MobclickAgent;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;
import io.microshow.rxffmpeg.RxFFmpegInvoke;
import qiu.niorgai.StatusBarCompat;

import static com.bigtotoro.shuiyincamera.editimage.Constacts.EXTRA_OUTPUT;

//homefragment点击开始制作进入这个主页

public class VideoMainEditActivity extends AppCompatActivity {
    public static final String TAG = "video-concat";
    private FrameLayout frameLayout;
    private VideoView videoView;

    int frameWidth, frameHeight;
    int videoWidth, videoHeight, videoRotation, videoDuration;

    private String path;
    private float scale;
    private SeekBar seekBar;
    private MediaPlayer mMediaPlayer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_main_edit);
        StatusBarCompat.setStatusBarColor(this, getResources().getColor(R.color.font_0));

        if (getIntent().getStringExtra("path") != null) {
            path = getIntent().getStringExtra("path");
        }

        //添加友盟事件统计
        MyUtils.addUmengEvent(VideoMainEditActivity.this, "video_main", "视频编辑总界面");

        initRecycleView();
        initEditMenuData();

        frameLayout = findViewById(R.id.frame);
        initVideoView();

        VideoUtil.checkVideoDir();
    }

    private void initEditMenuData() {
        //视频分割 //视频拼接 //视频滤镜//视频加水印//添加音乐//分离音频 //去水印 //加减速 //倒放 //GIF导出
        VideoEditMenu menu0 = new VideoEditMenu();
        menu0.setId(0);
        menu0.setName("分割");
        menu0.setImgPath(R.mipmap.menu_crop);  //视频分割
        dataList.add(menu0);
        VideoEditMenu menu1 = new VideoEditMenu();
        menu1.setId(1);
        menu1.setName("拼接");
        menu1.setImgPath(R.mipmap.menu_colect);  //视频拼接
        dataList.add(menu1);
        VideoEditMenu menu2 = new VideoEditMenu();
        menu2.setId(2);
        menu2.setName("滤镜");
        menu2.setImgPath(R.mipmap.menu_lvjing);  //视频滤镜
        dataList.add(menu2);
        VideoEditMenu menu3 = new VideoEditMenu();
        menu3.setId(3);
        menu3.setName("加水印");
        menu3.setImgPath(R.mipmap.menu_add_water);  //视频加水印
        dataList.add(menu3);
        VideoEditMenu menu4 = new VideoEditMenu();
        menu4.setId(4);
        menu4.setName("添加音乐");
        menu4.setImgPath(R.mipmap.menu_add_music); //添加音乐
        dataList.add(menu4);
        VideoEditMenu menu5 = new VideoEditMenu();
        menu5.setId(5);
        menu5.setName("分离音频");
        menu5.setImgPath(R.mipmap.menu_extract_bg); //分离音频
        dataList.add(menu5);
        VideoEditMenu menu6 = new VideoEditMenu();
        menu6.setId(6);
        menu6.setName("去水印");
        menu6.setImgPath(R.mipmap.menu_remove_water); //去水印
        dataList.add(menu6);
        VideoEditMenu menu7 = new VideoEditMenu();
        menu7.setId(7);
        menu7.setName("加减速");
        menu7.setImgPath(R.mipmap.menu_change_speed); //加减速
        dataList.add(menu7);
        VideoEditMenu menu8 = new VideoEditMenu();
        menu8.setId(8);
        menu8.setName("倒放");
        menu8.setImgPath(R.mipmap.menu_daofang); //倒放
        dataList.add(menu8);
        VideoEditMenu menu9 = new VideoEditMenu();
        menu9.setId(9);
        menu9.setName("GIF导出");
        menu9.setImgPath(R.mipmap.menu_gif); //GIF导出
        dataList.add(menu9);

        if (recycleAdapter != null) {
            recycleAdapter.setData(dataList);
            recycleAdapter.notifyDataSetChanged();
        }
    }

    private Handler handler = new Handler();
    Runnable updateThread = new Runnable() {
        @Override
        public void run() {
            if (!pause && mMediaPlayer != null) {
                seekBar.setProgress(mMediaPlayer.getCurrentPosition());
                Log.i("当前进度", "当前进度==== " + mMediaPlayer.getCurrentPosition());
                handler.postDelayed(this, 100); //每0.1秒更新一次进度
            }
        }
    };
    private boolean pause = false;
    private ImageView iv_video_click;
    private void initVideoView() {
        iv_video_click = findViewById(R.id.iv_video_click);
        videoView = findViewById(R.id.video);
        seekBar = findViewById(R.id.opacitySeekBar);
        if (path == null || path.lastIndexOf(".") < 0) return; //检测路劲非空
        videoView.setVideoURI(Uri.parse(path));
        videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mediaPlayer) {
                mMediaPlayer = mediaPlayer;

                videoWidth = mediaPlayer.getVideoWidth();
                videoHeight = mediaPlayer.getVideoHeight();
                videoDuration = mediaPlayer.getDuration();
                seekBar.setMax(videoDuration);


                new Thread(updateThread).start();
                seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                    @Override
                    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                    }

                    @Override
                    public void onStartTrackingTouch(SeekBar seekBar) {
                        handler.removeCallbacks(updateThread);
                    }

                    @Override
                    public void onStopTrackingTouch(SeekBar seekBar) {
                        mMediaPlayer.seekTo(seekBar.getProgress());
                        handler.postDelayed(updateThread, 1000);
                    }
                });

                videoView.start();
                mediaPlayer.setLooping(true); //循环播放

                frameWidth = frameLayout.getWidth();
                frameHeight = frameLayout.getHeight();
                Log.d(TAG, "frame" + frameWidth + ":" + frameHeight);
                Log.d(TAG, "video" + videoWidth + ":" + videoHeight);
//                Toast.makeText(MainActivity.this, frameWidth+":"+frameHeight, Toast.LENGTH_SHORT).show();

                //Get VideoView's current width and height
                int videoViewWidth = videoView.getWidth();
                int videoViewHeight = videoView.getHeight();

                float xScale = (float) videoViewWidth / videoWidth;
                float yScale = (float) videoViewHeight / videoHeight;

                //For Center Crop use the Math.max to calculate the scale
                //float scale = Math.max(xScale, yScale);
                //For Center Inside use the Math.min scale.
                //I prefer Center Inside so I am using Math.min
                scale = Math.min(xScale, yScale);

                float scaledWidth = scale * videoWidth;
                float scaledHeight = scale * videoHeight;

                //Set the new size for the VideoView based on the dimensions of the video
                ViewGroup.LayoutParams layoutParams = videoView.getLayoutParams();
                layoutParams.width = (int) scaledWidth;
                layoutParams.height = (int) scaledHeight;
                videoView.setLayoutParams(layoutParams);

                videoView.invalidate();

                Log.d(TAG, "scaledWidth " + scaledWidth + " scaledHeight " + scaledHeight);
                Log.d(TAG, "video after set params");
                Log.d(TAG, "videoView" + videoView.getWidth() + ":" + videoView.getHeight());
                Log.d(TAG, "videoView getx " + videoView.getX() + " and getY " + videoView.getY());
            }

        });
        frameLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (pause){  //点击了播放
                    pause = false;
                    videoView.start();
                    videoView.seekTo(mMediaPlayer.getCurrentPosition());
                    iv_video_click.setImageResource(R.mipmap.jz_pause_pressed);
                    handler.postDelayed(updateThread, 200);
                    iv_video_click.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            iv_video_click.setVisibility(View.INVISIBLE);
                        }
                    },500);
                }else {  //点击了暂停
                    pause = true;
                    videoView.pause();

                    iv_video_click.setImageResource(R.mipmap.jz_play_pressed);
                    iv_video_click.setVisibility(View.VISIBLE);
                }
            }
        });

    }

    private RecyclerView recyclerView;    //全部视频列表（按日期分类）
    private List<VideoEditMenu> dataList = new ArrayList<>();
    private SimpleAdapter3<VideoEditMenu> recycleAdapter = null;

    private void initRecycleView() {
        recyclerView = findViewById(R.id.recyclerView);
        LinearLayoutManager layoutManager = new LinearLayoutManager(VideoMainEditActivity.this);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setNestedScrollingEnabled(false);  //防止recycleview和srcollview滑动冲突，必须加不然无法顺畅滑动列表
        recyclerView.addItemDecoration(new SpaceItemDecoration(
                CompatResourceUtils.getDimensionPixelSize(this, R.dimen.space_10),
                CompatResourceUtils.getDimensionPixelSize(this, R.dimen.space_0)
        ));
        recycleAdapter = new SimpleAdapter3<VideoEditMenu>(
                R.layout.item_main_edit) {
            @Override
            protected void onBindDataViewHolder(@NonNull BaseViewHolder holder, int position, VideoEditMenu menu) {
                holder.setText(R.id.tv_name, menu.getName());

                ImageView avatar = holder.findViewById(R.id.iv_photo);
                avatar.setImageResource(menu.getImgPath());

                View item = holder.findViewById(R.id.item);
                item.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int position = (int) v.getTag();
                        VideoEditMenu menu = dataList.get(position);
                        //根据点击位置跳转不同页面
                        //视频分割 //视频拼接 //视频滤镜//视频加水印//添加音乐//分离音频 //去水印 //加减速 //倒放 //GIF导出
                        if (menu.getId() == 0) { //视频分割
                            startActivity(new Intent(VideoMainEditActivity.this, VideoCropActivity.class)
                                    .putExtra("path", path));
                        } else if (menu.getId() == 1) { //视频拼接,跳转选择视频界面，然后在跳转视频拼接界面
                            Log.i("视频处理", "视频加水印");
                            MyUtils.checkReadAndWritePermission(VideoMainEditActivity.this, new MyUtils.IntegerCallback() {
                                @Override
                                public void callback(int data) {
                                    if (data > 0) {
                                        mRequestCode = JUMP_TO_VIDEO_COLECT;
                                        selectFromAblum();
                                    }
                                }
                            });
                        } else if (menu.getId() == 2) { //视频滤镜
                            startActivity(new Intent(VideoMainEditActivity.this, VideoFilterActivity.class)
                                    .putExtra("path", path));
                        } else if (menu.getId() == 3) { //视频加水印
                            startActivity(new Intent(VideoMainEditActivity.this, VideoAddWater2Activity.class)
                                    .putExtra("path", path));
                        } else if (menu.getId() == 4) { //添加音乐
                            startActivity(new Intent(VideoMainEditActivity.this, VideoMusicActivity.class)
                                    .putExtra("path", path));
                        } else if (menu.getId() == 5) { //分离音频
                            startActivity(new Intent(VideoMainEditActivity.this, VideoTrimmerActivity.class)
                                    .putExtra(VideoTrimmerActivity.VIDEO_PATH_KEY, path)
                                    .putExtra("mode", "extract_bg"));
                        } else if (menu.getId() == 6) { //去水印
                            startActivity(new Intent(VideoMainEditActivity.this, VideoRemoveWaterActivity.class)
                                    .putExtra("path", path));
                        } else if (menu.getId() == 7) { //加减速
                            startActivity(new Intent(VideoMainEditActivity.this, VideoSpeedActivity.class)
                                    .putExtra("path", path));
                        } else if (menu.getId() == 8) { //倒放
                            startActivity(new Intent(VideoMainEditActivity.this, VideoTrimmerActivity.class)
                                    .putExtra(VideoTrimmerActivity.VIDEO_PATH_KEY, path)
                                    .putExtra("mode", "daofang"));
                        } else if (menu.getId() == 9) { //GIF导出
                            startActivity(new Intent(VideoMainEditActivity.this, VideoTrimmerActivity.class)
                                    .putExtra(VideoTrimmerActivity.VIDEO_PATH_KEY, path)
                                    .putExtra("mode", "gif"));
                        }
                    }
                });
                item.setTag(holder.getAdapterPosition());


            }
        };
        recycleAdapter.bindRecyclerView(recyclerView);
    }


    private int mRequestCode = -1;
    public static final int REQUEST_PERMISSON_SORAGE = 1;
    public static final int JUMP_TO_VIDEO_COLECT = 1018;

    /**
     * 从相册选择编辑图片
     */
    private void selectFromAblum() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            openAblumWithPermissionsCheck();
        } else {
            openAblum();
        }
    }

    private void openAblumWithPermissionsCheck() {
        if (ActivityCompat.checkSelfPermission(VideoMainEditActivity.this,
                Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(VideoMainEditActivity.this,
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                    REQUEST_PERMISSON_SORAGE);
            return;
        }
        openAblum();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == REQUEST_PERMISSON_SORAGE
                && grantResults.length > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            openAblum();
            return;
        }
    }

    private void openAblum() {
        switch (mRequestCode) {
            case JUMP_TO_VIDEO_COLECT://视频拼接
                Log.i("视频处理", "openAblum 视频拼接"); //最多5个
                PictureSelector.create(this).openGallery(PictureMimeType.ofVideo())
                        .previewVideo(true).maxSelectNum(4).selectionMode(PictureConfig.MULTIPLE).videoMinSecond(1).forResult(mRequestCode);
                break;
        }
    }

    private File outputFile;
    private List<LocalMedia> paths;
    public static final int ACTION_REQUEST_EDITIMAGE = 9;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /**
         * 选择图片后返回
         * **/
        if (resultCode == RESULT_OK) {
            String filepath = data.getStringExtra("imgPath");
            //原始图片存储地址
            switch (requestCode) {
                case JUMP_TO_VIDEO_COLECT: //视频拼接
                    Log.i("视频处理", "onActivityResult 视频拼接");
                    List<VideoItem> videos = new ArrayList<>();
                    if (path != null && path.lastIndexOf(".") > 0) {
                        videos.add(VideoUtil.createVideoItem(path));
                    }
                    List<LocalMedia> selectList7 = PictureSelector.obtainMultipleResult(data);
                    if (selectList7.size() > 0) {
                        for (LocalMedia media : selectList7) {
                            videos.add(VideoUtil.createVideoItem(media.getPath()));
                        }
                    }
                    ModelSingle.getInstance().setMode2(videos);
                    startActivity(new Intent(VideoMainEditActivity.this, VideoConcatActivity.class));
                    break;
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        pause = false;
        MobclickAgent.onPageStart("VideoSplice2Activity");//统计页面
        MobclickAgent.onResume(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        pause = true;
//        if (mMediaPlayer!=null){
//            mMediaPlayer.pause();
//        }
        MobclickAgent.onPageEnd("VideoSplice2Activity");//统计页面
        MobclickAgent.onPause(this);
    }

}
